package dreamCookGame;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import javax.media.*;
import javax.swing.Timer;

public class Video {
	String _name;
	URL _cutSceneURL;
	@SuppressWarnings("restriction")
	Player _player;
	Component _videoComponent;
	Timer _timer;
	int _MILLESECONDS_BETWEEN_FRAMES;
	boolean _videoFinished;
	
	public Video(String name, int duration) {
		_name = name;
		_MILLESECONDS_BETWEEN_FRAMES = duration*1000;
		_videoFinished = false;
	}
	
	@SuppressWarnings({ "restriction", "deprecation" })
	public void loadResources(References reference){
		if(_name == "test")
			try {
				File videoFile = reference.getVideoFile(_name);
				_cutSceneURL = videoFile.toURL();
			} 
		    catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			try{
				_player = Manager.createRealizedPlayer(_cutSceneURL);
			}
			catch( NoPlayerException noPlayerException ) {
				System.err.println( "No media player found" );
			} 
			catch ( CannotRealizeException cannotRealizeException ) {
				System.err.println( "Could not realize media player" );
			}
			catch ( IOException iOException ) {
				System.err.println( "Error reading from the source" );
			} 

			_player.setMediaTime(new Time(0.0));
			_player.setRate((float) 1.0);
			Time stopTime = new Time(10.0);
			//_player.setStopTime(stopTime);
			_videoComponent = _player.getVisualComponent();
			
	}	
	
	private void createTimer() {
		_timer = new Timer(_MILLESECONDS_BETWEEN_FRAMES, new ActionListener() {
			public void actionPerformed(ActionEvent event) {
				_timer.stop();
				_videoFinished = true;
				_timer.restart();
			}
		});
		_timer.start();
			
	}
	
	@SuppressWarnings("restriction")
	public void play(){
		_player.start();
		createTimer();
	}
	
	@SuppressWarnings("restriction")
	public void stop(){
		_player.stop();
	}
	
	@SuppressWarnings("restriction")
	public void restart(){
		_player.setMediaTime(new Time(0.0));
		_videoFinished = false;
	}
}
